package juc.CAS;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * AtomicReference的使用
 */
class Account2{
    public AtomicReference<BigDecimal> balance;
    public Account2(BigDecimal balance){
        this.balance=new AtomicReference<>(balance);
    }

    public BigDecimal getBalance(){
        return balance.get();
    }

    public void withDraw(BigDecimal amount){
        while (true){
            BigDecimal pre = balance.get();
            BigDecimal next = pre.subtract(amount);
            if(balance.compareAndSet(pre,next)){
                break;
            }
        }
    }
}
public class CASDemo2 {
    public static void main(String[] args) {
        Account2 account2 = new Account2(new BigDecimal(10000));
        List<Thread> ts = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account2.withDraw(new BigDecimal(10));
            }));
        }
        long start = System.nanoTime();
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println(account2.getBalance()
                + " cost: " + (end-start)/1000_000 + " ms");
    }

    }
